package io.renren.modules.basedata.service.impl;

import cn.com.taiji.common.manager.net.http.binclient.ApiRequestException;
import cn.com.taiji.sdk.comm.ETCCommHelper;
import cn.com.taiji.sdk.model.comm.protocol.sdts.basics.issuer.AgencyUploadRequest;
import cn.com.taiji.sdk.model.comm.protocol.sdts.basics.issuer.AgencyUploadResponse;
import cn.com.taiji.sdk.model.comm.protocol.sdts.expand.GasStationOperatorUploadRequest;
import cn.com.taiji.sdk.model.comm.protocol.sdts.expand.GasStationOperatorUploadResponse;
import io.renren.common.utils.CreateFileUtil;
import io.renren.common.utils.DateUtil;
import io.renren.common.utils.GUID;
import io.renren.modules.basedata.dao.AgencyUploadDao;
import io.renren.modules.basedata.dao.GasStationOperatorUploadDao;
import io.renren.modules.basedata.dao.OperlogDao;
import io.renren.modules.basedata.entity.tbl_Operlog;
import io.renren.modules.basedata.entity.tbl_agency;
import io.renren.modules.basedata.entity.tbl_gasStationOperator;
import io.renren.modules.basedata.service.AgencyUploadService;
import io.renren.modules.basedata.service.GasStationOperatorUploadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Service
public class GasStationOperatorUploadServiceImpl implements GasStationOperatorUploadService {
    private Logger log = LoggerFactory.getLogger(getClass());
    @Autowired
    private GasStationOperatorUploadDao gasStationOperatorUploadDao;
    @Autowired
    private OperlogDao operlogDao;

    @Override
    public String gasStationOperatorUpload() throws Exception {

        log.info("开始获取加油站ETC运营方信息！");
        int operResult = 0;
        List<tbl_gasStationOperator> list = null;
        tbl_gasStationOperator gasStationOperator = null;
        tbl_Operlog operlog = new tbl_Operlog();
        list = getGasStationList();//获取加油站ETC运营方信息
        if(list!=null&&list.size()>0){
            for(int i=0;i<list.size();i++){
                gasStationOperator = list.get(i);
                //加油站ETC运营方信息上传及变更接口
                GasStationOperatorUploadRequest request = new GasStationOperatorUploadRequest();
                request.setId(gasStationOperator.getId());
                request.setName(gasStationOperator.getName());
                request.setContact(gasStationOperator.getContact());
                request.setTel(gasStationOperator.getTel());
                request.setAddress(gasStationOperator.getAddress());
                request.setOperation(gasStationOperator.getFlag());

                //获取发送文件名
                String fileName = ETCCommHelper.getFileName(request, "65"); //发送方编码（新疆--65）
                try{
                    //指定响应的协议模型，调用upload发送数据
                    GasStationOperatorUploadResponse response = ETCCommHelper.sdtsUpload(fileName, request, GasStationOperatorUploadResponse.class);
                    log.info("上传加油站ETC运营方信息成功，服务器返回："+response.toJson());
                    if(response!=null&&response.getInfo().equals("成功！")){
                        //更新上传标志

                        if(gasStationOperatorUploadDao.updateGasStationOperator(gasStationOperator.getId())==1){
                            log.info("更新加油站ETC运营方信息表上传标志成功!");
                            operResult = 1;
                            operlog = getOperlog(26,1,gasStationOperator.getId(),fileName,operResult, response.getInfo(),"上传成功，更新成功");
                        }else{
                            log.info("更新加油站ETC运营方信息表上传标志成功!");
                            operlog = getOperlog(26,1,gasStationOperator.getId(),fileName ,operResult,response.getInfo(),"上传成功，更新失败");
                        }
                        operlogDao.insertlog(operlog);
                        //sqlMapClient.insert("operlog_ORACLE.insertlog",operlog);
                    }else{
                        log.info("上传加油站ETC运营方信息失败!失败原因："+response.getInfo());
                        gasStationOperatorUploadDao.updateGasStationOperatorError(gasStationOperator.getId());
                       // sqlMapClient.update("tollBaseInfo_ORACLE.updateGasStationOperatorError",gasStationOperator.getId());

                        //getOperlog（操作类型，传输类型，发送文件名，接收文件名，操作结果，部中心返回结果，说明）
                        operlog = getOperlog(26,1 ,gasStationOperator.getId(),fileName ,0,response.getInfo(), response.toJson());
                        operlogDao.insertlog(operlog);
                        //sqlMapClient.insert("operlog_ORACLE.insertlog",operlog);
                    }
                }catch(IOException e){
                    log.error("上传加油站ETC运营方信息失败！错误信息："+e.getMessage());
                    gasStationOperatorUploadDao.updateGasStationOperatorError(gasStationOperator.getId());
                   // sqlMapClient.update("tollBaseInfo_ORACLE.updateGasStationOperatorError",gasStationOperator.getId());

                    operlog = getOperlog(26, 1, gasStationOperator.getId(), fileName, 0,"IO异常", "出现IO异常，数据上传失败："+e.getMessage());
                    operlogDao.insertlog(operlog);
                    //sqlMapClient.insert("operlog_ORACLE.insertlog",operlog);
                    e.printStackTrace();
                    continue;
                }catch (ApiRequestException apie) {
                    log.error("上传加油站ETC运营方信息失败！错误信息："+apie.getMessage());
                    gasStationOperatorUploadDao.updateGasStationOperatorError(gasStationOperator.getId());
                   // sqlMapClient.update("tollBaseInfo_ORACLE.updateGasStationOperatorError",gasStationOperator.getId());

                    operlog = getOperlog(26, 1, gasStationOperator.getId(), fileName, 0,String.valueOf(apie.getErrCode()), "出现ApiRequestException异常，数据上传失败："+apie.getMessage());
                    operlogDao.insertlog(operlog);
                    //sqlMapClient.insert("operlog_ORACLE.insertlog",operlog);
                    apie.printStackTrace();
                    continue;
                }
            }
            return "上传加油站ETC运营方信息结束！";
        }else{
            return "无加油站ETC运营方信息，上传结束...";
        }

    }

    //获取加油站ETC运营方信息
    @SuppressWarnings("unchecked")
    public List<tbl_gasStationOperator> getGasStationList() throws IOException{
        List<tbl_gasStationOperator> list;
        try{
            list = gasStationOperatorUploadDao.getGasStationOperatorList();
           // list = sqlMapClient.queryForList("tollBaseInfo_ORACLE.getGasStationOperatorList");
        }catch(Exception e){
            e.printStackTrace();
            log.error("获取加油站ETC运营方信息失败！错误信息：",e);
            throw new IOException("获取加油站ETC运营方信息失败:"+e.getMessage());
        }
        return list;
    }

    //获取operlog信息
    public tbl_Operlog getOperlog(int operType,int softType,String sendFileName,String reFileName,int operResult,String reResult, String content){
        tbl_Operlog operlog = new tbl_Operlog();
        operlog.setWastesn(new GUID().toString());
        operlog.setOperTime(new Date());
        operlog.setOpertype(operType);
        operlog.setSoftType(softType);
        operlog.setSendFileName(sendFileName);
        operlog.setReFileName(reFileName);
        operlog.setOperResult(operResult);
        operlog.setReResult(reResult);
        operlog.setContent(content);
        return operlog;
    }
}
